package com.mdinfo.base.interceptor;

import com.alibaba.fastjson.JSON;
import com.mdinfo.base.common.bean.CommonResult;
import com.mdinfo.base.common.bean.Ref;
import com.mdinfo.base.utils.SystemUtil;
import com.mdinfo.base.utils.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/12/4.
 * token校验拦截器
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
//        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //过滤掉ajax跨域options请求
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            System.out.println("OPTIONS");
            return false;
        }

        boolean result = true;
        CommonResult<Object> tokenError = null;
        String token = request.getHeader("Authorization");

        //检查token是否存在
        if(StringUtil.isEmpty(token)){
            tokenError = Ref.tokenError("没有token");
            result = false;
        }
        //token校验是否正确
        else{
            String errToken = token + "";
            SystemUtil.validate(errToken,request.getRequestURI());
        }
        if(!result){
            response.getWriter().print(JSON.toJSONString(tokenError));
        }
        return result;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
